// import { getStyle } from 'element-plus/lib/utils/dom/index.js';
const getStyle = window.getComputedStyle;
/**
 * show-overflow-tooltip for text
 * 当text没有被折叠时，不显示tooltip
 */
const tooltipAutoShow = {
  created(el, binding, vnode) {
    let tooltipNode = vnode.children.find(
      childrenCmpt => childrenCmpt.component?.type.name == 'ElTooltip'
    );
    if (tooltipNode) {
      // 用于给带tooltip的按钮加上点击后消失
      // 带参数isButton（原本是预设的几种值，容易和超长显示冲突）
      let { content, type = '' } = tooltipNode.props;
      // const presets = ['New', 'Edit', 'Delete', 'View'];
      if (content && type === 'button') {
        el.addEventListener('click', function (e) {
          let defalutDisabled = tooltipNode.component.props.disabled;
          if (!defalutDisabled) {
            tooltipNode.component.props.disabled = true;
            setTimeout(() => {
              tooltipNode.component.props.disabled = defalutDisabled;
            }, 200);
          }
        });
      } else {
        // 其他非按钮，超长显示
        el.addEventListener('mouseenter', e => {
          tooltipNode.component.props.disabled = true;
          const range = document.createRange();
          range.setStart(el, 0);
          range.setEnd(el, el.childNodes.length);
          const rangeWidth = Math.round(range.getBoundingClientRect().width);
          const padding =
            (parseInt(getStyle(el).getPropertyValue('padding-left'), 10) || 0) +
            (parseInt(getStyle(el).getPropertyValue('padding-right'), 10) || 0);
          if (rangeWidth + padding > el.offsetWidth || el.scrollWidth > el.offsetWidth) {
            tooltipNode.component.props.disabled = false;
          }
        });
      }
    }
  },
};

export default tooltipAutoShow;
